//
//  DrivingLicenseController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/6/15.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
//行驶证补办
class DrivingLicenseController:BaseController{
    var flag = 0//标识区分证件
    var license_file_1 = ""
    var license_file_2 = ""
    var license_file_3 = ""
    var license_file_4 = ""
    var drivingTable:UITableView!//数据表格
    var drivingCell:DrivingLicenseCell!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupNavBar(title: "行驶证补办", isback: true, appearWay: 2, isright: false)//自定义导航
        //初始化表格
        drivingTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH,width:kScreenW,height:kScreenH - kStatusBarH - kNavigationBarH),style: UITableViewStyle.plain)
        drivingTable?.delegate = self
        drivingTable?.dataSource = self
        drivingTable?.separatorStyle = UITableViewCellSeparatorStyle.none
        drivingTable?.rowHeight = commonViewH + 7*oTop + 3*oLabelH + 5*oImgH + remarkH + cellH + 10///根据cell页面最后一个组件Y坐标算
        self.view.addSubview(drivingTable)
    }
}
extension DrivingLicenseController{
    //提交按钮
    func submitDrivingBtn() {
        if "" ==  self.license_file_1{
            checkAlertFun(message: "请选择登记证书！")
        }else if "" == self.license_file_2 {
            checkAlertFun(message: "请选择车辆照片！")
        }else if "" == self.license_file_3 || "" == self.license_file_4 {
            checkAlertFun(message: "请选择身份证信息！")
        }else {
            submitDriving()
        }
    }
    //提交行驶证审核信息
    func submitDriving(){
        if reachability.isReachable {
            let urlString = "\(projectUrl)/order/other/commit/drivinglicense/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            let parameter:[String:Any] = [
                "orderData":"{\"driveLicense_1\":\"\(self.license_file_1)\",\"driveLicense_2\":\"\(self.license_file_2)\",\"driveLicense_3\":\"\(self.license_file_3)\",\"driveLicense_4\":\"\(self.license_file_4)\",\"remark\":\"\(drivingCell.remark.text!)\"}"
            ]
            Alamofire.request(urlString, method: .post, parameters: parameter, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        let alertController = UIAlertController(title: alertTitle, message: "行驶证补办提交成功！", preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "确定", style: .default, handler:{
                            (UIAlertAction) -> Void in
                            let mainVC = UINavigationController(rootViewController: MainViewController())
                            app.window?.rootViewController = mainVC
                        })
                        alertController.addAction(okAction)
                        self.present(alertController, animated: true, completion: nil)
                    }
                    else{
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    func choicePicture(sender: UIButton){
        self.flag = sender.tag
        centerY = sender.convert(sender.bounds, to: toast.container).origin.y
        let alert = UIAlertController()
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.cameraFunc()
        }
        let choseAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.photoFunc()
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        self.present(alert, animated: true, completion: nil)
    }
    //调用相机
    func cameraFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
    //调用相册
    func photoFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
}
extension DrivingLicenseController :UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        //显示的图片
        let image:UIImage =  info[UIImagePickerControllerOriginalImage] as! UIImage
        if reachability.isReachable {
            uploadImage(img: image)//上传图片到服务器
            picker.dismiss(animated: true, completion: nil)//图片控制器退出
            toast.showLoadingView(x: oImgLeft + oImgW + 10, y: centerY)
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //上传图片
    func uploadImage(img:UIImage){
        let toUrl = "\(projectUrl)/file/upload/drivinglicense/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        let imageData = UIImageJPEGRepresentation(img, 1.0)!
        //使用Alamofire上传
        Alamofire.upload(multipartFormData: { (mult) in
            mult.append(imageData, withName: "file", fileName: "drivinglicense\(self.flag).png", mimeType: "image/png")
        }, to: toUrl, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    if jsonDate["success"] == true {
                        let photoID = jsonDate["rdata"].rawValue as! String
                        if(1 == self.flag){
                            self.license_file_1 = photoID
                            self.drivingCell.driveLicense_1.setImage(img, for: .normal)
                        }
                        if(2 == self.flag){
                            self.license_file_2 = photoID
                            self.drivingCell.driveLicense_2.setImage(img, for: .normal)
                        }
                        if(3 == self.flag){
                            self.license_file_3 = photoID
                            self.drivingCell.driveLicense_3.setImage(img, for: .normal)
                        }
                        if(4 == self.flag){
                            self.license_file_4 = photoID
                            self.drivingCell.driveLicense_4.setImage(img, for: .normal)
                        }
                    }else{
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                    toast.closeWin()
                }
            case .failure(let encodingError):
                print("ERROR RESPONSE: \(encodingError)")
            }
        })
    }
}
extension DrivingLicenseController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        drivingCell = tableView.dequeueReusableCell(withIdentifier: "drivingLicenseCellID") as? DrivingLicenseCell
        if drivingCell == nil {
            drivingCell = DrivingLicenseCell(style: UITableViewCellStyle.default,reuseIdentifier: "drivingLicenseCellID")
        }
        return drivingCell!
    }
}
